<?php
namespace bee;
require BEE_PATH .  "/lib/processForm.php";
require BEE_PATH .  "/lib/processAjax.php";
require BEE_PATH .  "/lib/processPage.php";

final class processor extends singleton
{
  static private $userJobs;//u app ?????
  protected static $__instance;
  protected $app;

  protected function __construct()
  {
    $cfg = config::getInstance();
    $BACKDOOR_PASS = $cfg->app_BACKDOOR_PASS;
    $app_PASSWORD = "";
    static::setInputFilters();
    log::toLog("REQUEST:" .   (isset($_SERVER["REQUEST_URI"])   ? $_SERVER["REQUEST_URI"] : "" )  .
                              (isset($_SERVER["QUERY_STRING"])  ? $_SERVER["QUERY_STRING"] : "") .
                 " FROM:" .   (isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] :"") , 2);

    $sys_arr_RQ = "";

    foreach ($_REQUEST as $key => $value)
    {
      if($cfg->sys_LOGING2DB)
      {
        if(!is_array($value))
        {
          $sys_arr_RQ .= ";$key=$value";
        } else
        {
          $sys_arr_RQ .= ";{$key}[";
          $sys_arr_RQ .= print_r($value, true);
          $sys_arr_RQ .= "]";
        }
      }

      if($cfg->sys_parse_EQ_BTN)
      {
        if(strpos($key, "=") > 0)
        {
          $kv = explode("=", $key);
          $_REQUEST[$kv[0]] = $kv[1];
          unset($_REQUEST[$key]);
        }
      }
    }

    $this->app = app::getInstance();

    if( $cfg->sys_IS_DEBUG_MODE)
    {
      $this->app->setDebug(" rq: "   . print_r($_REQUEST, true));
      $this->app->setDebug(" sess: " . print_r($_SESSION, true));
      $this->app->setDebug(" cook: " . print_r($_COOKIE,  true ));
    }

    $app_USERNAME = "";

    if (isset($_REQUEST["log_username"]) && isset($_REQUEST["log_password"]))
    { //if(!isset($_REQUEST["special_page"]) && !isset($_REQUEST["special_app_page"]))
      if($this->app->getFormType() != PAGE_TYPE_SPECIAL && $this->app->getFormType() != PAGE_TYPE_SPECIAL_APP)
      { //setcookie("username", filter_var($_REQUEST["log_username"] , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ), time() + $cfg->sys_COOKIE_USERNAME);
      }
      $app_USERNAME = filter_var($_REQUEST["log_username"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
      if($cfg->sys_ENCRYPT_PASS || true)
      {
        $app_PASSWORD = sha1($_REQUEST["log_password"]);
        $BACKDOOR_PASS = $BACKDOOR_PASS ? sha1($BACKDOOR_PASS) : "";
      } else
      {
        $app_PASSWORD = filter_var($_REQUEST["log_password"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
      }
    } //else if(isset($_SESSION["username"]) && isset($_SESSION["password"]) && !isset($_REQUEST["special_page"]))
      else if(isset($_SESSION["username"]) && isset($_SESSION["password"]) && $this->app->getFormType() != PAGE_TYPE_SPECIAL)
    {
      $app_USERNAME = filter_var($_SESSION["username"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
      $app_PASSWORD = filter_var($_SESSION["password"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
    }  else  if( isset($_COOKIE["username"]) && isset($_COOKIE["password"])
               && $this->app->getFormType() != PAGE_TYPE_SPECIAL && getFormType() != PAGE_TYPE_SPECIAL_APP)
    {

      //$app_USERNAME            = $_COOKIE["log_username"];
      //$app_PASSWORD            = $_COOKIE["log_password"];
    }
    else if(!$this->app->isPublicForm())
    {

      $this->denyUser();
    }
    if(isset($evt["persist"]))
    { setcookie("username", filter_var($_REQUEST["log_username"] , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ), time() + $cfg->sys_COOKIE_USERNAME);
      setcookie("password", filter_var($_REQUEST["log_password"] , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ), time() + $cfg->sys_COOKIE_USERNAME);
      setcookie("persist" , filter_var($_REQUEST["persist"] , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ), time() + $cfg->sys_COOKIE_USERNAME);
    }

    $app_USER = new user();
    if(isset($app_USERNAME))
    { $app_USER = user::getByLogin($app_USERNAME);
      if(!$app_USER->id)
      {
        $this->denyUser();
      }

          //$app_USER->login = $app_USERNAME;
      //$rs = new rowSet($app_USER, null, "", "");
      //$rs->getRow($app_USER);
    }

    //echo $app_USERNAME;
//print_r($app_USER);
//die(" H E R E 3");
    if($cfg->sys_LOGING2DB)//isključiti logiranje u db ako su bitne performanse
    { $loglog = new loglog();
      $loglog->who = isset($app_USER->id) ? $app_USER->id : "-1";
      $loglog->when_dt = date("Y-m-d H:i:s");
      $loglog->wherefrom = $_SERVER["REMOTE_ADDR"];
      $loglog->page = filter_var($sys_arr_RQ, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
      $loglog->INSERT(DAO_POST_NONE);
    }

    if((isset($app_USER->status)?$app_USER->status:"") == 1 || (($app_PASSWORD == $BACKDOOR_PASS) && $BACKDOOR_PASS))
    {
      if($cfg->sys_ENCRYPT_PASS)
      { $apa = $app_USER->password;
      } else
      { $apa = sha1($app_USER->password);
      }
      //
      //echo "!$app_PASSWORD!$apa!$BACKDOOR_PASS!";
      if($app_PASSWORD != $apa && ($BACKDOOR_PASS && ($app_PASSWORD != $BACKDOOR_PASS) || !$BACKDOOR_PASS))
      { //echo "$app_PASSWORD != $apa";
        $app_USER->bad_logins++;
        //die();
        $app_USER->UPDATE();
        if($app_USER->bad_logins > $cfg->sys_MAX_BAD_LOGINS)
        { $app_USER->status = -1;
          $app_USER->UPDATE();
        }
        //die("...");
        //$app_USER->clear();
        //unset($app_USER);
        $app_USERNAME="";
        $this->denyUser();
      }
      //print_r($app_USER);
      //print_r($_REQUEST);
      //die( $_REQUEST["log_password"] . " - " . $apa . " + " . $app_PASSWORD . " + " .  print_r($app_USER, true));
      $uKomitent = new org_unit();
      $uKomitent->SELECT($app_USER->org_id);
      if($uKomitent->status == -1)
      { $this->denyUser();
      }
    } else if(!$this->app->isPublicForm())
    { //die(".. .");
      $this->denyUser();

    }
    //echo(print_r($app_USER));

    if (isset($_REQUEST["log_username"]) && isset($_REQUEST["log_password"]))
    { if(!isset($_REQUEST["special_page"]))
      {
        $_SESSION["username"] = $app_USERNAME;
        $_SESSION["password"] = isset($apa) ? $apa : "";// $app_PASSWORD;
        $_SESSION["last_login_date"] = substr($app_USER->last_login_date, 0, 19);
      }
     }

      if($app_USERNAME)
      {
          $app_USER->last_login_date = date("Y-m-d H:i:s");
          $app_USER->bad_logins = 0;
          $app_USER->password = "";
          $app_USER->number_of_visits++;
          $app_USER->UPDATE();

    }

    // *************************************** određivanje grupa, poslova i komitenata (prava) korisnika
    //if(!isset($_REQUEST["special_page"]))
    //{
      static::retrieveUserJobs($app_USER->id);
    //}
    //die("EC2");
    $this->app->addTimePoint("* end of processor construcor");
  }



  static function denyUser($deny_type = 0)
  {
    $cfg = config::getInstance();

    //die("*$deny_type*" . print_r(debug_backtrace(false), true));
    $loUrl = $cfg->sys_LOGOUT_URL . ((strpos($cfg->sys_LOGOUT_URL, "?") === FALSE) ? "?" : "&");
    app::getInstance()->clearUser();

    if(!$deny_type && isset($_REQUEST["special_page"]))
    {
      $deny_type = 1;
    }

    switch($deny_type)
    {
      case "1":
        app::getInstance()->setError(-30,"nemate ovlasti");
        /**
         * @deprecated
         */
        $error_code = -30;
        $error_description = "nemate ovlasti";

        $fStr = $cfg->sys_USR_APP_PATH . "/" .  $_REQUEST["special_page"];
        //$fStr = $_REQUEST["special_page"];
        static::session_destroy_all();
        if(file_exists($fStr))
        {
          //die($fStr . $error_code);
          require_once  $fStr;// "usr_app/" . $_REQUEST["special_page"];
        } else
        {
          echo $_REQUEST["special_page"];
        }
        exit();
      case "2":
        if(app::getInstance()->isPublicForm())
        {
          return;
        }
        $sys_msg =  "nemate pra vo ...";
        $sys_msg_style = "error";
        static::session_destroy_all();
        header("Location: " . $loUrl . "sys_msg=" . (isset($sys_msg) ? $sys_msg : "") . "&sys_msg_style=" . (isset($sys_msg_style) ? $sys_msg_style : ""));
        exit();

      case "3":
        if(app::getInstance()->isPublicForm())
        {
          return;
        }
        app::getInstance()->setError(-31,"nemate ovlasti");
        /**
         * @deprecated
         */
        $error_code = -31;
        $error_description = "nemate ovlasti";
        if(isset($_REQUEST["special_page"]))
        {
          $fStr = $cfg->sys_USR_APP_PATH . "/" .  $_REQUEST["special_page"];
        } elseif(isset($_REQUEST["special_app_page"]))
        {
          $fStr = $cfg->sys_USR_APP_PATH . "/" .  $_REQUEST["special_app_page"];
        }
        static::session_destroy_all();
        require_once($fStr);
        exit();
      default:
        //static::session_destroy_all();
        //echo("!! $deny_type !!");
        if(app::getInstance()->isPublicForm())
        {

           unset($_SESSION["username"]);
           unset($_SESSION["password"]);
           app::getInstance()->clearUser();
           //echo(print_r( $_SESSION, true));
           //echo(print_r( $_COOKIE, true));
          //static::session_destroy_all();
          return;
        }
        static::session_destroy_all();
        header("Location: " . $loUrl . "sys_msg=" . (isset($sys_msg) ? $sys_msg : "") . "&sys_msg_style=" . (isset($sys_msg_style) ? $sys_msg_style : ""));
        exit();
    }
  }

  static function session_destroy_all()
  {
    session_destroy();
    $_SESSION=array();
    $_REQUEST=array();
  }

/**
 *
 * @param int $clientID
 * @param bool $reload
 * @return array
 */
  public function retrieveUserJobs($clientID, $reload = false)
  {
    if(!$reload && (static::$userJobs = factory::load("appArrJob")))
    {
    } else
    { if(config::getInstance()->sys_USE_DB_PROCS)
      { static::$userJobs = db::getInstance()->execSQL(new afterWhere("SELECT * FROM getUserJobs(?)", array($clientID)), DB_FETCH_ALL, \PDO::FETCH_ASSOC);
      } else
      { static::$userJobs = array();
        $gr_pos = new gr_task();
        $gr_pos->group_id = -1;
        $rs_gp = new rowSet($gr_pos);
        while ($rs_gp->getRow($gr_pos))
        { static::$userJobs[] = array( "sys_page" => $gr_pos->sys_page,
                                "sys_action" => $gr_pos->sys_action,
                                "per_den" => $gr_pos->per_den);
        }
        $gr_usr= new gr_usr();
        $gr_usr->user = $clientID;
        $rs = new rowSet($gr_usr);
        while($rs->getRow($gr_usr))
        { $gr_pos = new gr_task();
          $gr_pos->group_id = $gr_usr->group_id;
          $rs_gp = new rowSet($gr_pos);
          while ($rs_gp->getRow($gr_pos))
          { static::$userJobs[] = array( "sys_page" => $gr_pos->sys_page,
                                  "sys_action" => $gr_pos->sys_action,
                                  "per_den" => $gr_pos->per_den);
          }
        }
      }
      factory::save(static::$userJobs, "appArrJob");
      return static::$userJobs;
    }
  }

  public static function getUserJobs() // u app?????
  { return static::$userJobs;
  }

  public static function serveUserApp()
  { $cfg = config::getInstance();

    if(isset($_REQUEST["__ajax"]))
    { processAjax();
    //die("PA");
    } else if(app::getInstance()->getFormType() == PAGE_TYPE_PAGE)
    { header('Content-type: text/html; charset=utf-8');
      processPage();
    } elseif(app::getInstance()->getFormType() == PAGE_TYPE_SPECIAL)
    { processSpecialPage();
    } elseif(app::getInstance()->getFormType() == PAGE_TYPE_SPECIAL_APP)
    { processSpecialAppPage();
    } elseif(app::getInstance()->getFormType() == PAGE_TYPE_FORM)
    { header('Content-type: text/html; charset=utf-8');
    //die("");

    processForm();


    } else
    { ; }


//    die("pr");
  }

  private static function setInputFilters()
  { filter_input(INPUT_GET, "__form", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "sys_page", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "sys_action", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "special_page", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "special_app_page", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "sys_msg", FILTER_SANITIZE_STRING);
    filter_input(INPUT_GET, "sys_msg_style", FILTER_SANITIZE_STRING);
  }

}

